<template>
    <el-row v-if="isShow"  style="height: 100%;"  class="interface-test-container mt5">
        <el-row >
            <el-col :span="24">
                <div :style="{height:'12' , overflow:'auto',margin: '0px',padding: '5px'}">
                    <el-row>
                        <el-form ref="infMainRef" :model="form" :rules="rules" label-width="auto">
                            <el-row>
                                <!-- <el-col :span="8">
                                    <el-form-item label="接口编码" prop="deptCode">
                                        <el-input v-model="form.infCode" disabled="true"
                                                    placeholder="请输入接口编码"/>
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="接口名称" prop="deptName">
                                        <el-input v-model="form.infName" disabled="true"
                                                    placeholder="请输入接口名称"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item label="请求" prop="infMethod">
                                        <dictCombox v-model="form.infMethod" dictType="infMethod"
                                                    prop="infMethod"
                                                    disabled placeholder="请选择方法"></dictCombox>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label-width="0" label="" prop="infUrl">
                                        <el-input v-model="form.infUrl" disabled="true"
                                                    placeholder="请输入URL"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-row>
                </div>
            </el-col>
        </el-row>
        <el-row style="flex: 1;">
            <el-col :span="24">
                <div :style="{height:'100%' , overflow:'auto'}">
                    <el-tabs v-model="activeNameInf" @tab-click="clickTab" lazy="false" class="interface-test-tabs">
                        <el-tab-pane label="基础信息" name="infMain" class="flex-cloumn">
                            <el-form ref="infBaseRef" :model="form" :rules="rules" label-width="100px">
                                <el-row>
                                    <el-col :span="24" v-if="form.parentId !== 0">
                                        <el-form-item label="上级目录" prop="parentId">
                                            <el-tree-select
                                                    disabled="true"
                                                    style="width:100%"
                                                    v-model="form.parentId"
                                                    :data="infOptions"
                                                    :props="{ value: 'infId', label: 'infName', children: 'children' }"
                                                    value-key="infId"
                                                    placeholder="请选择上级目录"
                                                    check-strictly
                                            />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24">
                                        <el-form-item label="显示排序" prop="orderNum">
                                            <Numberinput v-model="form.orderNum" disabled="true"
                                                        precision="0" :min="'0'"/>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24" v-show="true">
                                        <el-form-item label="记住登录" prop="noLogin"
                                                    style="width:100%">
                                            <dictCombox v-model="form.noLogin" dictType="boolType"
                                                        prop="noLogin"
                                                        disabled="true"
                                                        placeholder="请输入记住登录"></dictCombox>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24" v-if="true">
                                        <el-form-item label="负责人" prop="leader" style="width:100%">
                                            <baseCombox url="/system/user/getUsercombobox"
                                                        :queryParam="{pageSize: 50}"
                                                        disabled="true"
                                                        valueField="userId" labelField="userName"
                                                        placeholder="请输入负责人" v-model="form.leader">
                                            </baseCombox>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="接口状态">
                                            <el-radio-group v-model="form.status" disabled="true">
                                                <el-radio
                                                        v-for="dict in sys_normal_disable"
                                                        :key="dict.dictValue"
                                                        :label="dict.dictValue"
                                                >{{ dict.dictLabel }}
                                                </el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>

                        </el-tab-pane>
                        <el-tab-pane label="请求头" name="header" class="flex-cloumn">
                            <el-form ref="infHeaderRef" :model="form" :rules="rules"
                                    label-width="100px">
                                    <el-form-item label="Content-Type" prop="contentType">
                                            <el-input v-model="form.contentType"
                                                    placeholder="" clearable disabled/>
                                        </el-form-item>
                                        <el-form-item label="auth名称" prop="authName">
                                            <el-input v-model="form.authName"
                                                    placeholder="" clearable/>
                                        </el-form-item>
                                        <el-form-item label="auth值" prop="authValue">
                                            <el-input v-model="form.authValue" placeholder="" clearable/>
                                        </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="请求参数" name="params" class="flex-cloumn test-tab-fill" >
                            <el-form :model="form" :rules="rules"
                                    label-width="auto">
                                <el-form-item>
                                    <el-button icon="Refresh" type="primary" @click="resetInfRequest" >格式化</el-button>
                                </el-form-item>
                                <el-form-item  label="" prop="infRequest" v-if="jsonEditView">
                                    <JsonEditorVue v-model="form.infRequestJson"
                                                :style="{width:'100%'}"
                                                class="editor"
                                                :current-mode="form.currentMode"></JsonEditorVue>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>

                        <el-tab-pane label="一键压测" name="sst" class="flex-cloumn">
                            <el-form ref="infSstRef" :model="form" :rules="rules" label-width="100px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="线程数" prop="concurrency">
                                            <Numberinput v-model="form.concurrency"
                                                        controls-position="left"
                                                        precision="0" :min="1" :max="100"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12" v-if="true">
                                        <el-form-item label="循环次数" prop="round" style="width:100%">
                                            <Numberinput v-model="form.round" controls-position="left"
                                                        precision="0" :min="1"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="超时时间" prop="timeOut">
                                            <el-input v-model="form.timeOut" @input="handleInput" maxlength="10">
                                                <template #append>ms</template>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="2" v-if="true">
                                        <el-form-item>
                                            <el-button
                                                    type="primary"
                                                    style="margin: 3px 3px"
                                                    @click="handleBatch"
                                                    :disabled="stsButtonDisabled"
                                                    v-hasPermi="['testmanage:onekeyTest:run']"
                                            >开始压测
                                            </el-button>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <!--详情抽屉-->
                                <el-row>
                                    <el-drawer v-model="showDetailDrawer" :before-close="handleClose" size="61.8%" direction="rtl" custom-class="detail-drawer">
                                        <detail ref="sstDetailRef" v-if="showDetailDrawer" @handleExport="handleExport" />
                                    </el-drawer>
                                </el-row>
                            </el-form>

                        </el-tab-pane>
                        <el-tab-pane label="测试报告" name="reportMain" class="flex-cloumn">
                                <el-row>
                                    <div class="center-top">
                                        <span v-if="reportCheckList.length === 0" class="item" style="padding-left: 20px;">我的报告</span>
                                        <span v-if="reportCheckList.length !== 0" class="item" style="padding-left: 20px;">已选 {{ reportCheckList.length }} 项</span>
                                        <el-link v-if="reportCheckList.length !== 0" style="font-size: 15px; margin-left: 10px;margin-bottom: 3px;font-weight: 550" :underline="false" @click="removeReport">移除</el-link>
                                    </div>
                                </el-row>
                                <xTable ref="reportTableRef" refId="reportTableRef" :data="reportList" border 
                                    @selection-change="handleReportSelectionChange" v-loading="reportLoading">
                                    <template #columList>
                                        <el-table-column label="测试场景" fixed align="left" prop="reportName" width="200" :show-overflow-tooltip="true"/>
                                        <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
                                            <template #default="scope">
                                                <dict-tag :options="reportStatus" :value="scope.row.status"/>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="类型" align="center" prop="reportType" :show-overflow-tooltip="true">
                                            <template #default="scope">
                                                <dict-tag :options="reportType" :value="scope.row.reportType"/>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="结果" align="left" width="150" >
                                            <template #default="scope">
                                                <el-progress v-if="scope.row.status === '0'" class="custom-progress" :show-text="false" color="#46D6A0" :percentage="scope.row.percentage"></el-progress>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="循环次数" align="right" prop="concurrency"/>
                                        <el-table-column label="线程数" align="right" prop="round"/>
                                        <el-table-column label="测试时间" align="center" width="150" prop="requestTime"/>
                                        <el-table-column label="测试人" align="center" prop="createBy"  width="150" :show-overflow-tooltip="true"/>
                                        <el-table-column label="操作" fixed="right" align="right"  width="55"   class-name="small-padding fixed-width">
                                            <template #default="scope">
                                                <el-link type="primary" :underline="false" :icon="Download" v-hasPermi="['testmanage:report:exportReport']" v-if="scope.row.status == '0'" style="font-size: 16px; vertical-align: middle;" @click.stop="handleExport(scope.row.reportId)">
                
                                                </el-link>
                                                <el-link type="primary" :underline="false" :icon="Delete" v-hasPermi="['testmanage:report:remove']" style="font-size: 16px; vertical-align: middle;" @click.stop="deleteReport(scope.row.reportId)" class="ml5"> 
                                            
                                                </el-link>
                                            </template>
                                        </el-table-column>
                                    </template>
                                </xTable>
                                <el-pagination
                                    small
                                    background
                                    layout="->,prev, pager, next"
                                    :total="queryReportParams.total"
                                    class="mt-4"
                                    :current-page="queryReportParams.pageNum"
                                    :page-size="queryReportParams.pageSize"
                                    @current-change="handlePageChange"
                                />
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-col>
        </el-row>
    </el-row>
</template>
<script setup name="OneKeyTab">
import {getCurrentInstance, nextTick, reactive, ref, watch} from "vue";
import Detail from '@/views/testmanage/onekeysst/detail'
import Numberinput from '@/lz/base/number'
import { ElMessageBox } from 'element-plus'
import JsonEditorVue from 'json-editor-vue3'
import {requestServeBatch} from "@/api/testmanage/inf";
import { deleteReports,queryAtReport } from "@/api/testmanage/autoTest";
import { isNotVoid,isVoid } from '@/utils/util';
import { Delete,Download } from '@element-plus/icons-vue'

const {proxy} = getCurrentInstance();
const {sys_normal_disable, reportStatus, reportType} = proxy.useDict("sys_normal_disable", "reportStatus", "reportType");

const reportCheckList = ref([]);
const activeNameInf = ref('infMain');
const jsonEditView = ref(true)
const stsButtonDisabled = ref(false);
const showDetailDrawer = ref(false)
const reportList = ref([]);
const reportLoading = ref(false)

const data = reactive({
    queryReportParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0
    },
    infListForm: {
        menuId: '',
        infName: '',
        status: 0,
        infs: []
    },
    rules: {
        infCode: [{required: true, message: "接口编码不能为空", trigger: "change"}],
        concurrency: [{required: true, message: "并发数不能为空", trigger: "change"}],
        round: [{required: true, message: "轮次不能为空", trigger: "change"}],
    },
})

const {queryReportParams,infListForm} = toRefs(data);

const props = defineProps({
    form: {
        type: Object,
        default: {
          concurrency: 1,
          round: 1
        }
    },
    infOptions: {
        type: Array,
        default: []
    },
    globalEnv: {
        type: String,
        default: ''
    },
    isShow:{
        type:Boolean,
        default:false,
    }
})

watch(() => props.form, (nv, ov) => {
 },{ deep: true, immediate: true })


function handleBatch() {
    proxy.$refs["infSstRef"].validate(valid => {
        if(!(isNotVoid(props.globalEnv) || isNotVoid(props.form.infEnv))) {
            proxy.$modal.msgError("请选择至少一个环境");
            return
        }
        stsButtonDisabled.value = true;
        props.form.infRequest = JSON.stringify(props.form.infRequestJson);
        let data = Object.assign({}, props.form)
        if(isNotVoid(props.globalEnv)) {
            data.infEnv = props.globalEnv
        }
        requestServeBatch(data).then(response => {
            if (response.code !== 200) {
                stsButtonDisabled.value = false;
                proxy.$modal.msgError(response.msg);
            } else {
                showDetailDrawer.value = true
                nextTick(() => {
                    proxy.$refs.sstDetailRef.startTimer()
                    props.form.reportId = response.result
                    let count = data.concurrency * data.round
                    let threadNumber = data.concurrency
                    let infLength = 1
                    let mcs = data.mcs
                    proxy.$refs.sstDetailRef.getDetail(response.result, count, threadNumber, infLength, mcs)
                })
                proxy.$modal.msgSuccess("线程资源准备成功");
            }
        });
    })
}

//选中报告
function handleReportSelectionChange(selection) {
    if (selection.length == 0) {
        reportCheckList.value = []
    } else {
        reportCheckList.value = selection.map(item => item.reportId);
    }
}

//关闭抽屉调用方法
function handleClose() {
    if(proxy.$refs.sstDetailRef.stopFlag) {
        if (proxy.$refs.sstDetailRef.stopRun) {
            showDetailDrawer.value = false
            stsButtonDisabled.value = false;
            proxy.$refs.sstDetailRef.resetData()
        } else {
            ElMessageBox.confirm('确定要关闭页面吗？关闭后将在后台运行', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                showDetailDrawer.value = false
                stsButtonDisabled.value = false;
                proxy.$refs.sstDetailRef.resetData()
            }).catch(() => { });
        }
    } else {
        showDetailDrawer.value = false
        stsButtonDisabled.value = false;
        proxy.$refs.sstDetailRef.resetData()
    }

}

function clickTab(tab, event) {
    switch(tab.index) {
        case "4":
            reportList.value = []
            getReportList();
            break;
    }
}

//查询测试报告
function getReportList() {
    reportLoading.value = true
    queryReportParams.value.infId = props.form.infId
    queryAtReport(queryReportParams.value).then(response => {
        reportLoading.value = false
        queryReportParams.value.total = response.total
        reportList.value = response.rows
    });
}

function handleExport(id) {
    proxy.download("/inf/exportReport", Object.assign({}, {reportId: id}));
}

function handlePageChange(currentPage) {
    queryReportParams.value.pageNum = currentPage
    getReportList()
}


//批量移除报告
function removeReport() {
    deleteReports(reportCheckList.value).then(response => {
        proxy.$modal.msgSuccess("删除成功!");
        getReportList()
    });
}

//移除单个报告
function deleteReport(id) {
    let ids = []
    ids.push(id)
    deleteReports(ids).then(response => {
        proxy.$modal.msgSuccess("删除成功!");
        getReportList()
    });
}

// 格式化
function resetInfRequest() {
    jsonEditView.value = false;
    if (isVoid(props.form.infRequestJson)) {
        props.form.infRequestJson = "JSON不能为空或JSON格式错误,请检查数据";
        jsonEditView.value = true;
        return
    }
    const jsonString = JSON.stringify(props.form.infRequestJson);
    const formattedJson = JSON.parse(jsonString); 
    props.form.infRequestJson = formattedJson;
    props.form.currentMode = 'code';
    jsonEditView.value = true;
}

const handleInput = () => {
    props.form.timeOut = props.form.timeOut.replace(/[^\d]/g, '')
}
</script>

<style scoped>
.el-row {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    box-sizing: border-box;
    width: 100%;
}

/deep/ .jsoneditor-menu a {
    color: #3883fa !important;
    /*display: none*/
}

/deep/ .jsoneditor {
    border: thin solid #ffffff !important;

}

/deep/ .el-drawer__container {
    position: relative;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
}
</style>

<style lang="scss" scoped>
.interface-test-container{
    align-content: flex-start;
    flex-direction: column;
    &>.el-row{
        &:last-child{
            flex: 1;
        }
    }
}
.el-card {
    :deep(.el-card__body){
        height: 100%;
    }
}
.interface-tree{
    :deep(.el-card__body){
      display: flex;
      flex-direction: column;
    }
}
.interface-test-tabs{
    height: 100%;
    display: flex;
    flex-direction: column;
    :deep(.el-tabs__content) {
        flex: 1;
        .el-tab-pane{
            height: 100%;
            overflow:auto;
        }
        .test-tab-fill{
            .el-form {
                height: 100%;
                display: flex;
                flex-direction: column;
                .el-form-item:last-child{
                    flex: 1;
                    .container.editor{
                        height: 100%;
                    }
                                    
                }
            }
           
        }
    }
}


:deep(div.jsoneditor-outer.has-main-menu-bar)  {
    margin-bottom: -35px !important;
    padding-bottom: 35px !important;
}
</style>
<style scoped lang="scss">
:deep(.detail-drawer){
    .el-drawer__header{
        height:0;
        position:relative;
        margin-bottom:0;
    }
    .el-drawer__body{
        padding-top:0;
    }
}
</style>
